<?php
namespace app\home\controller;

use app\common\model\HelpGetRich;
use app\common\model\UserWalletRich;
use app\common\model\UserWalletRichFreeze;
use app\common\model\AppointmentRich as AppointmentRichModel;

use app\common\component\user\UserService;
use app\common\component\help_get_rich\HelpGetRichService;
use app\common\component\user_wallet_rich\UserWalletRichService;
use app\common\component\user_wallet_rich_log\UserWalletRichLogService;
use app\common\component\user_wallet_rich_freeze\UserWalletRichFreezeService;

class WithdrawRich extends ControllerBase {
	public function _initialize() {
		$this -> checkLogin();
	}

	public function index() {
		$userId = \think\Session::get('user_id');
		$this -> view -> assign('helpGetRichs', HelpGetRich::where('user_id', $userId) -> order('status ASC, help_get_rich_id DESC') -> paginate(10, true));

		$resultUserWalletRich = (new UserWalletRichService) -> getUserWalletRichId($userId);
		$this -> view -> assign('user_wallet_rich', $resultUserWalletRich['data']['user_wallet_rich']);

        return $this -> view -> fetch();
	}

	public function withdraw() {
		$resultUserWalletRich = (new UserWalletRichService) -> getUserWalletRichId(\think\Session::get('user_id'));
		$this -> view -> assign('user_wallet_rich', $resultUserWalletRich['data']['user_wallet_rich']);

		$resultUser = (new UserService) -> getUser();
    	$this -> view -> assign('user', $resultUser['data']['user']);

		return $this -> view -> fetch();
	}

	public function handleWithdraw() {
		$post = $this -> request -> post();

		$WITHDRAW_RICH_MULTIPLE = getParam('WITHDRAW_RICH_MULTIPLE');
		if(($post['price'] % $WITHDRAW_RICH_MULTIPLE) != 0) {
    		echo '<meta charset="utf-8"><script>alert("必须要以' . $WITHDRAW_RICH_MULTIPLE . '倍起提!");window.history.go(-1);</script>';exit;
    	}

		if($post['price'] > getParam('WITHDRAW_RICH_PRICE_MAX')) {
    		echo '<meta charset="utf-8"><script>alert("您提现的' . $post['price'] . '金额大于指定金额!");window.history.go(-1);</script>';exit;
    	}

		$resultCheckPayPassword = (new UserService()) -> checkPayPassword($post['pay_password']);
    	if($resultCheckPayPassword['code'] !== 0) {
    		echo '<meta charset="utf-8"><script>alert("' . $resultCheckPayPassword['message'] . '!");window.history.go(-1);</script>';exit;
    	}

		$userId = \think\Session::get('user_id');

		$resultUserWalletRich = (new UserWalletRichService) -> getUserWalletRichId($userId);
    	if($resultUserWalletRich['data']['user_wallet_rich'] -> price < $post['price']) {
    		echo '<meta charset="utf-8"><script>alert("您的剩余金额不足!");window.history.go(-1);</script>';exit;
    	}

		$findHelpAppointmentRich = AppointmentRichModel::where('user_id', $userId) -> where('status', 0) -> find();
		if(!$findHelpAppointmentRich) {
			echo '<meta charset="utf-8"><script>alert("请先预约订单!");window.history.go(-1);</script>';exit;
		}

		$WITHDRAW_RICH_IN_TIME = getParam('WITHDRAW_RICH_IN_TIME');
		$findHelpGetRich = HelpGetRich::where('user_id = ' . $userId .' AND status IN(0,1,2) AND begin_time > "' . (time() - ($WITHDRAW_RICH_IN_TIME * 60 * 60)) . '"') -> find();
		if($findHelpGetRich) {
			echo '<meta charset="utf-8"><script>alert("您的富豪提现在' . $WITHDRAW_RICH_IN_TIME . '小时内，请耐心等候匹配!");window.history.go(-1);</script>';exit;
		}

		\think\Db::startTrans();
		try {
			$resultUserWalletRichLog = (new UserWalletRichLogService) -> log(3, 0, $post['price'], $userId, '富豪提现', 1);
			if($resultUserWalletRichLog['code'] !== 0) {
				throw new \Exception($resultUserWalletRichLog['message']);
			}

			$resultHelpGetRich = (new HelpGetRichService()) -> withdraw($post['price']);
	    	if($resultHelpGetRich['code'] !== 0) {
	    		throw new \Exception($resultHelpGetRich['message']);
	    	}

			if(!UserWalletRich::where('user_id', $userId) -> setDec('price', $post['price'])) {
				throw new \Exception('富豪钱包扣款失败');
			}
			\think\Db::commit();
		} catch(\Exception $e) {
			\think\Db::rollback();

			echo '<meta charset="utf-8"><script>alert("' . $e -> getMessage() . '!");window.location.href="/withdraw/rich";</script>';exit;
		}
		echo '<meta charset="utf-8"><script>alert("' . $resultHelpGetRich['message'] . '!");window.location.href="/withdraw/rich";</script>';exit;
	}

	public function freeze() {
		$userId = \think\Session::get('user_id');
		$this -> view -> assign('userWalletRichFreezes', UserWalletRichFreeze::where('user_id', $userId) -> order('is_freeze ASC, user_wallet_rich_freeze_id DESC') -> paginate(10, true));

		$this -> view -> assign('sumUserWalletRichFreeze', UserWalletRichFreeze::where('user_id', $userId) -> where('is_freeze', 0) -> sum('remain_price'));

		return $this -> view -> fetch();
	}

	public function draw() {
		$get = $this -> request -> get();

		$drawUserWalletRichFreezeService = (new UserWalletRichFreezeService) -> draw($get['user_wallet_rich_freeze_id'], $get['key']);
		echo '<meta charset="utf-8"><script>alert("' . $drawUserWalletRichFreezeService['message'] . '!");window.location.href="/withdraw/rich/freeze";</script>';exit;
	}

	public function cancel() {
		$gethelpGetRichId = $this -> request -> get('help_get_rich_id', 0, 'int');
		if($gethelpGetRichId <= 0) {
			echo '<meta charset="utf-8"><script>alert("非法操作!");window.location.href="/withdraw/rich";</script>';exit;
		}

		$getHelpGetRich = HelpGetRich::get(['help_get_rich_id' => $gethelpGetRichId]);
		if(!$getHelpGetRich) {
			echo '<meta charset="utf-8"><script>alert("订单不存在!");window.location.href="/withdraw/rich";</script>';exit;
		}

		$getHelpGetRich -> status = 8;
		$getHelpGetRich -> begin_time = time();

		\think\Db::startTrans();
		try {
			if(!$getHelpGetRich -> save()) {
				throw new \Exception('取消失败, save!');
			}

			$resultUserWalletRichLog = (new UserWalletRichLogService) -> log(4, 1, $getHelpGetRich -> price, $getHelpGetRich -> user_id, '取消订单', 1);
			if($resultUserWalletRichLog['code'] !== 0) {
				throw new \Exception($resultUserWalletRichLog['message']);
			}

			if(!UserWalletRich::where('user_id', $getHelpGetRich -> user_id) -> setInc('price', $getHelpGetRich -> price)) {
				throw new \Exception('取消失败');
			}
			\think\Db::commit();
		} catch(\Exception $e) {
			\think\Db::rollback();

			echo '<meta charset="utf-8"><script>alert("' . $e -> getMessage() . '!");window.location.href="/withdraw/rich";</script>';exit;
		}
		echo '<meta charset="utf-8"><script>alert("取消成功!");window.location.href="/withdraw/rich";</script>';exit;

	}
}
?>